<template>
  <!--  用户组管理-->
  <div class="userGrouplist">
    <div class="sibarLeft">
      <el-button
        type="primary"
        style="margin-bottom: 5px;"
        size="mini"
        :disabled="!bomCost('usergroup:insert')"
        @click.native="addTree"
      >
        {{ $t('market.treeAdd') }}<!--添加节点-->
      </el-button>
      <el-input v-model.trim="filterText" placeholder="输入关键字进行过滤" />
      <el-tree
        ref="tree"
        :data="treeData"
        :props="defaultProps"
        node-key="fid"
        default-expand-all
        highlight-current
        :filter-node-method="filterNode"
        @node-click="handleNodeClick"
      />
    </div>
    <div class="table-content">
      <div style="margin-left: 40px;margin-bottom: 10px;">
        <el-button type="primary" size="mini" @click="insetTree">
          {{ $t('btn.save') }}
        </el-button>
        <el-button type="danger" size="mini" @click="delUserGroup">
          {{ $t('btn.del') }}
        </el-button>
      </div>
      <jc-form ref="userForm" :option-value="optionValue" :options="options" />
    </div>
  </div>
</template>

<script>
import jcForm from '@/components/Form'
import { uuid } from 'vue-uuid'
import {
  insertUsergroup,
  updateUsergroup,
  delUsergroup,
  queryStaffTypeList
} from '@/api/basicManagement/userGroup'
import { queryUsergroup } from '@/api/basicManagement/userslist'
export default {
  name: 'UserGroup',
  components: {
    jcForm
  },
  data: () => ({
    treeData: [], // 树数据
    defaultProps: {
      // 配置选项
      children: 'details',
      label: 'fname'
    },
    filterText: '', // 查询条件
    clickTree: {}, // 点击树获取值
    clickNode: {}, // 树层级
    optionValue: {}, // 表单数据
    options: {}, // 表单控件
    fparentid: 0, // 保存数据需要向后端发送的id
    fid: 0 // 更新数据的id,也是删除数据的id
  }),
  watch: {
    /** 过滤*/
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getUserGroup()
    this.getForm()
  },
  methods: {
    /** 获取数据*/
    async getUserGroup() {
      const data = {
        name: this.filterText
      }
      const { data: res } = await queryUsergroup(data)
      this.treeData = res
    },
    /** 新增*/
    insetTree() {
      /** 校验表单合法性*/
      const valid = this.$refs.userForm.handleRefData()
      if (!valid) {
        return
      }
      /** 只有optionValue改变时staffType才会变化*/
      const { fnumber, fname, fdescripTion, staffType } = this.optionValue
      /** 修改所需参数，只判断一个参数*/
      /** 如果当前的表单有数据那么直接调用修改接口,不经过新增*/
      if (this.clickTree.fnumber) {
        const data = {
          fid: this.fid,
          fnumber,
          fname,
          fdescription: fdescripTion,
          staffType
        }
        updateUsergroup(data).then(res => {
          const { code, message } = res
          if (code !== 0) {
            this.$message.warning(message)
            return
          }
          this.getUserGroup()
          this.$message({ showClose: true, message: message, type: 'success' })
        })
        return
      }
      /** 新增所需数据*/
      const insertData = {
        fparentid: this.fparentid,
        fnumber,
        fname,
        staffType,
        fdescription: fdescripTion
      }
      /** 调用接口，保存数据*/
      insertUsergroup(insertData).then(res => {
        const { code, message } = res
        if (code !== 0) {
          this.$message.warning(message)
          return
        }
        this.getUserGroup()
        this.$message({ showClose: true, message: message, type: 'success' })
      })
    },
    /** 删除*/
    delUserGroup() {
      const fid = this.fid
      if (!fid) {
        this.$message.warning('请选择树节点再选删除!')
        return
      }
      if (this.clickNode.id === 1) {
        this.$message.warning('不能删除首条数据')
        return
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delUsergroup({ fid }).then(res => {
            const { code, message } = res
            if (code !== 0) {
              this.$message.warning(message)
              return
            }
            this.$message({ showClose: true, message: message, type: 'success' })
            /** 删除id清空*/
            this.fid = null
            /** 表单数据初始化*/
            this.optionValue = {}
            /** 树控件数据更新*/
            this.getUserGroup()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    /** 过滤*/
    filterNode(value, data) {
      if (!value) return true
      return data.fname.indexOf(value) !== -1
    },
    /** 点击树节点*/
    handleNodeClick(data, node) {
      /** 保存时需要的数据*/
      this.clickNode = node
      const { key } = node.parent
      this.fparentid = key === undefined ? 0 : key // 保存id
      /** 点击树节点，表单展示数据*/
      this.clickTree = data
      const { fnumber, fname, fdescripTion, fid, staffType } = this.clickTree
      this.optionValue = { fnumber, fname, fdescripTion, staffType }
      this.fid = fid /** 赋值更新id*/
    },
    /** 添加节点*/
    addTree() {
      if (JSON.stringify(this.clickTree) === '{}') {
        this.$message.warning('请点击节点才能新增节点')
        return
      }
      const clickTree = this.clickTree
      const treeData = {
        fid: 0, // 避免重复更新
        fparentId: uuid.v1(),
        fnumber: '', // 组别编码
        fname: '新增节点', // 组别名称
        fdescripTion: '', // 描述
        children: []
      }
      if (!clickTree.details) {
        this.$set(clickTree, 'details', [])
      }
      clickTree.details.push(treeData)
    },
    /** 初始化数据*/
    async getForm() {
      const { data: res } = await queryStaffTypeList()
      const staffTypeArray = res.map(item => {
        const { fname, staffType } = item
        return { label: fname, value: staffType }
      })
      this.options = {
        fnumber: {
          label: this.$t('market.groupnum'),
          labelWidth: '120px',
          spacing: true,
          span: 24,
          rules: [
            { required: true, message: '请输入组别编码', trigger: 'blur' }
          ]
        },
        fname: {
          label: this.$t('market.groupname'),
          labelWidth: '120px',
          spacing: true,
          span: 24,
          rules: [
            { required: true, message: '请输入组别名称', trigger: 'blur' }
          ]
        },
        staffType: {
          label: this.$t('market.staffType'),
          labelWidth: '120px',
          type: 'select',
          spacing: true,
          selectItems: staffTypeArray,
          span: 24,
          rules: [
            { required: true, message: '请选择员工类型', trigger: 'blur' }
          ]
        },
        fdescripTion: {
          label: this.$t('market.descrip'),
          type: 'textarea',
          textarea: true,
          span: 24,
          rules: [{ required: true, message: '请输入描述', trigger: 'blur' }]
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
.userGrouplist {
  @include listBom;
  display: flex;
  flex-direction: row;
  height: calc(100vh - 100px);
  .sibarLeft {
    width: 20%;
    min-width: 200px;
    height: 100%;
    overflow: auto;
    padding-right: 20px;
    border-right: 1px solid #eee;
  }
  .table-content {
    width: 50%;
    margin-left: 10px;
  }
}
</style>
